package com.kura.uednews.fragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import com.kura.uedews.R;
import com.kura.uednews.MainActivity;
import com.kura.uednews.uednewsApplication;
import com.kura.uednews.dantri.NewsFeed;
import com.kura.uednews.dantri.NewsItem;
import com.kura.uednews.db.newsDB;
import com.kura.uednews.model.Categories;
import com.kura.uednews.ultilities.Community;
import com.kura.uednews.ultilities.FileIO;

import android.app.Application;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView.FindListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class fragment_news_list extends Fragment {

	TextView titleFragment;
	ListView newsListView;

	Community comm;
	uednewsApplication application;
	int choice;

	FileIO io;
	newsDB db;

	private NewsFeed feed;
	NewsAdapter adapter;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = inflater.inflate(R.layout.fragment_news_list, container,
				false);
		return view;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onActivityCreated(savedInstanceState);

		// component fragment
		titleFragment = (TextView) getActivity().findViewById(
				R.id.titleFragment);
		newsListView = (ListView) getActivity().findViewById(R.id.newsListView);
		// get instance application
		application = (uednewsApplication) getActivity().getApplication();

		// get instance FileIO
		io = new FileIO(getActivity().getApplicationContext());

		// get instance database
		db = new newsDB(getActivity().getApplicationContext());

		// choice from MainActivity
		choice = application.getChoice();

		// switch 3 choice
		switch (choice) {
		case 1:
			titleFragment.setText("Thông báo UED");
			break;
		case 6:
			titleFragment.setText("Dân Trí trang chủ");
			break;
		default:
			titleFragment.setText("VnExpress trang chủ");
			break;
		}

		// set event handler for listview
		newsListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				NewsItem item = (NewsItem) adapter.getItem(position);
				application.setDescription(item.getDescription());
				application.setLink(item.getLink());
				application.setTitle(item.getTitle());

				FragmentTransaction tx = getFragmentManager()
						.beginTransaction();
				tx.replace(R.id.main, android.app.Fragment.instantiate(
						getActivity().getApplicationContext(),
						"com.kura.uednews.fragment.fragment_news_detail"));
				tx.commit();
			}
		});
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		switch (choice) {
		case 1:
			titleFragment.setText("Thông báo UED");
			
			ArrayList<Categories> listCate = db.getListSubscribe();
			
			for(int i=0; i< listCate.toArray().length;i++){
				new DownloadFeed(listCate.get(i).getId(),1).execute();
			}	
			
			break;
		case 6:
			titleFragment.setText("Dân Trí trang chủ");
			new DownloadFeed(89, 2).execute();
			break;
		default:
			break;
		}

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub

		return super.onOptionsItemSelected(item);
	}

	class DownloadFeed extends AsyncTask<Void, Void, Void> {

		// 1 - UED
		// 2 - DANTRI
		// 3 - VnExpress
		int type;
		int id;

		public DownloadFeed(int id, int type) {
			this.id = id;
			this.type = type;
			
//			if(feed != null && id != 1){
//				feed.clearItems();
//			}
			
		}

		@Override
		protected Void doInBackground(Void... params) {
			io.downloadFile(db.getLinkById(id));
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			Log.d("News reader", "Feed downloaded");
			new ReadFeed(type).execute();
		}
	}

	class ReadFeed extends AsyncTask<Void, Void, Void> {

		// 1 - UED
		// 2 - DANTRI
		int type;

		public ReadFeed(int type) {
			this.type = type;
		}

		@Override
		protected Void doInBackground(Void... params) {
			
			NewsFeed tmp = io.readFile(this.type);
		
			if(feed == null){
				feed = new NewsFeed();
			}
			
			for (int i = 0; i < tmp.getItemCount(); i++) {
				feed.addItem(tmp.getItem(i));
			}
			
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			Log.d("News reader", "Feed read");
			fragment_news_list.this.updateDisplay();
		}
	}

	public void updateDisplay() {
		// if (feed == null) {
		// titleTextView.setText("Unable to get RSS feed");
		// return;
		// }

		// set the title for the feed
		// titleTextView.setText(feed.getTitle());

		// get the items for the feed
		List<NewsItem> items = feed.getAllItems();

		// create and set the adapter
		adapter = new NewsAdapter(getActivity(), items);
		newsListView.setAdapter(adapter);

		Log.d("News reader", "Feed displayed");
	}
}

class NewsAdapter extends BaseAdapter {

	Context context;
	List<NewsItem> listNews;
	ImageView imageView;
	TextView description;

	public NewsAdapter(Context context, List<NewsItem> items) {
		// TODO Auto-generated method stub
		this.context = context;
		listNews = items;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return listNews.toArray().length;
	}

	@Override
	public Object getItem(int position) {
		// TODO Auto-generated method stub
		return listNews.get(position);
	}

	@Override
	public long getItemId(int position) {
		// TODO Auto-generated method stub
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		View row = null;
		if (convertView == null) {
			LayoutInflater inflater = (LayoutInflater) context
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			row = inflater.inflate(R.layout.custom_news_row1, parent, false);
		} else {
			row = convertView;
		}
		description = (TextView) row.findViewById(R.id.titleNewsDetails);
		description.setText(listNews.get(position).getTitle());
		return row;
	}

}